<template>
  <el-card>
    <el-row :gutter="20">
      <el-col :span="5">
        <el-button type="primary" @click="open('add')">{{
          $t('table.adduser')
        }}</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        :width="item.width"
        :fixed="item.fixed"
        :prop="item.prop"
        :label="$t(`table.${item.label}`)"
        v-for="(item, index) in options"
        :key="index"
      >
        <template #default="scope" v-if="item.prop === 'action'">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            @click="editOpen('edit', scope.row)"
          >
          </el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="deleteUser(scope.row, scope.$index)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <Dialog
      :visible.sync="visible"
      :type="type"
      @done="reload"
      :userInfo="userInfo"
    ></Dialog>
  </el-card>
</template>

<script>
import { options } from './options'
import EditDialogVue from './components/Dialog.vue'

export default {
  name: 'users',
  components: {
    Dialog: EditDialogVue
  },
  data() {
    return {
      tableData: [],
      options: options,
      visible: false,
      type: '',
      userInfo: {}
    }
  },
  mounted() {
    this.getUsersList()
  },
  methods: {
    /* 刷新表格 */
    reload() {
      this.getUsersList()
    },
    //获取用户列表
    async getUsersList() {
      if (localStorage.getItem('Info')) {
        const data = JSON.parse(localStorage.getItem('Info')) ?? []
        this.tableData = data
      }
    },
    open(type) {
      this.type = type
      this.userInfo = {}
      this.visible = true
    },
    editOpen(type, row) {
      this.type = type
      this.userInfo = row
      this.visible = true
    },
    deleteUser(row, index) {
      this.$confirm(this.$t('dialog.deleteTitle'), '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          var arr = JSON.parse(localStorage.getItem('Info'))
          const _arr = arr.filter((el) => {
            return el.id !== row.id
          })
          localStorage.setItem('Info', JSON.stringify(_arr))
          this.getUsersList()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped></style>
